package lifecycle;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.Locale;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;

import bean.IDirectoryInfo;

public class MyFileLogger implements IDirectoryInfo, MessageSourceAware{
	private String fileName;
	private String filePath;
	private BufferedWriter writer;
	private MessageSource messageSource;
	@PostConstruct
	public void openFile() throws FileNotFoundException{
		System.out.println("open file ...");
		File logFile=new File(filePath, fileName+".txt");
		writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(logFile,true)));
	}
	public void log(Object logInfo) throws IOException{
		writer.write(new Date().toString()+","+logInfo+"\r\n");
		writer.flush();
		
		System.out.println("log info:"+logInfo);
		
		//显示消息
		showMessage(logInfo);
	}
	@PreDestroy
	public void closeFile() throws IOException{
		writer.close();
		System.out.println("close file ...");
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public String getFilePath() {
		return filePath;
	}
	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}
	public BufferedWriter getWriter() {
		return writer;
	}
	public void setWriter(BufferedWriter writer) {
		this.writer = writer;
	}
	@Override
	public String getPath() {
		return filePath;
	}
	@Override
	//该方法为MessageSourceAware的方法
	public void setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
	}
	public MessageSource getMessageSource() {
		return messageSource;
	}
	
	//显示多语言消息
	private void showMessage(Object logInfo){
		String msg = messageSource.getMessage("fileLogger.prompt",
							new Object[]{logInfo, new Date()},
							Locale.getDefault());
		System.out.println("------------------info-----------------");
		System.out.println(msg);
	}
}
